<style>
    html, body {
        margin: 0!important;
        padding: 0!important;
    }
</style>

<title>Promises and RecordRTC</title>
<h1>Promises and RecordRTC</h1>

<br>
<button id="btn-start-recording">Start Recording</button>
<button id="btn-stop-recording" disabled>Stop Recording</button>

<hr>
<video controls autoplay playsinline></video>

<script src="/RecordRTC.js"></script>
<script>
const video = document.querySelector('video');

async function stopRecordingCallback() {
    video.srcObject = null;
    let blob = await recorder.getBlob();
    video.src = URL.createObjectURL(blob);
    recorder.stream.getTracks(t => t.stop());

    // reset recorder's state
    await recorder.reset();

    // clear the memory
    await recorder.destroy();

    // so that we can record again
    recorder = null;
}

let recorder; // globally accessible

document.getElementById('btn-start-recording').onclick = async function() {
    this.disabled = true;
    let stream = await navigator.mediaDevices.getUserMedia({video: true, audio: true});
    video.srcObject = stream;
    recorder = new RecordRTCPromisesHandler(stream, {
        type: 'video'
    });
    await recorder.startRecording();
    
    // helps releasing camera on stopRecording
    recorder.stream = stream;

    document.getElementById('btn-stop-recording').disabled = false;

    // if you want to access internal recorder
    const internalRecorder = await recorder.getInternalRecorder();
    console.log('internal-recorder', internalRecorder.name);

    // if you want to read recorder's state
    console.log('recorder state: ', await recorder.getState());
};

document.getElementById('btn-stop-recording').onclick = async function() {
    this.disabled = true;
    await recorder.stopRecording();
    stopRecordingCallback();
    document.getElementById('btn-start-recording').disabled = false;
};
</script>

<footer style="margin-top: 20px;"><small id="send-message"></small></footer>
<script src="https://www.webrtc-experiment.com/common.js"></script>
